//
// Created by 17775 on 2024/11/18.
//

#ifndef RAYCI_COMMON_2DVIEW_H
#define RAYCI_COMMON_2DVIEW_H

#include <QWidget>
#include "../qcustomplot.h"

QT_BEGIN_NAMESPACE
namespace Ui { class Common_2DView; }
QT_END_NAMESPACE

class Common_2DView : public QWidget {
Q_OBJECT

signals:
    void showOptions();
    void getCurrentY(double currentY);
    void updateEllipse(double x, double y, double radiusX, double radiusY, double angle);

private slots:
//    void onMouseMove(const QMouseEvent *event) const;
    void onMousePress(const QMouseEvent *event);
    void onMouseMove(const QMouseEvent *event);
    void onMouseRelease(const QMouseEvent *event);

public:
    explicit Common_2DView(QWidget *parent = nullptr);
    ~Common_2DView() override;
    QCPItemPixmap* getImageItem() {
        return imageItem;
    }
    QCustomPlot *getCustomPlot() {
        return customPlot;
    }

    QCPCurve *getEllipse() {
        return ellipseCurve;
    }
    void clear();
    int nSizeX, nSizeY;
    void initEllipses(double dPositionX_px, double dPositionY_px, double dMajor_px, double dMinor_px, double dAngle_deg = 0.0) const;
    void setImageSize() const;
    void processCCDImageData(const QImage &image) const;
    void processFloatData(std::vector<float> &vecData);
    void visibelImage(bool vis) const;
    void clearImage() const;

private:
    Ui::Common_2DView *ui;
    QCPItemPixmap *imageItem = nullptr;
    QCustomPlot *customPlot = nullptr;
    QCPCurve *ellipseCurve = nullptr;
    QCPCurve *ellipseCurveSelected = nullptr;  // 选中状态的椭圆
    QCPItemText *coordinateLabel = nullptr;
    QMenu *m_contextMenu = nullptr;
    QCPItemLine *hArrow = nullptr;
    QCPItemLine *vArrow = nullptr;

    std::vector<float> _vecData;
    float getDataAt(int x, int y) const;

    bool isDraggingXCrossSectionLine = false;
    bool isMoving = false;
    bool isSelected = false;
    bool nearEllipseEdge = false;
    QPointF lastMousePos;

    // 椭圆参数存储
    double m_centerX = 640.0;
    double m_centerY = 512.0;
    double m_radiusX = 500.0;  // 半轴长度
    double m_radiusY = 500.0;
    double m_angle = 0.0;      // 角度（度）

    // 辅助方法
    void updateEllipseDisplay();
    double calculateDistanceToEllipseBoundary(const QPointF &mousePos) const;
    QPointF rotatePoint(const QPointF& point, const QPointF& center, double angleDeg) const;
    QPointF inverseRotatePoint(const QPointF& point, const QPointF& center, double angleDeg) const;
};

#endif //RAYCI_COMMON_2DVIEW_H
